package cn.iocoder.yudao.module.ems.service.outbound;

import cn.iocoder.yudao.module.ems.controller.admin.outbound.vo.OutboundInfoCreateReqVO;
import cn.iocoder.yudao.module.ems.controller.admin.outbound.vo.OutboundInfoRespVO;
import cn.iocoder.yudao.module.ems.convert.outbound.OutboundInfoConvert;
import cn.iocoder.yudao.module.ems.dal.dataobject.spares.SparesDO;
import cn.iocoder.yudao.module.ems.dal.dataobject.outbound.OutboundInfoDO;
import cn.iocoder.yudao.module.ems.dal.mysql.spares.SparesMapper;
import cn.iocoder.yudao.module.ems.dal.mysql.outbound.OutboundInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.ems.enums.ErrorCodeConstants.SPARES_ITEMNO_NOTEXISTS;
import static cn.iocoder.yudao.module.ems.enums.ErrorCodeConstants.OUTBOUND_NOT_EXISTS;

/**
 * 出库信息 Service 实现类
 *
 * @author dason
 */
@Service
@Validated
public class OutboundInfoServiceImpl implements OutboundInfoService {

    @Resource
    private OutboundInfoMapper outboundInfoMapper;

    @Resource
    private SparesMapper sparesMapper;

    private void validateOutboundInfoExists(Long id) {
        if (outboundInfoMapper.selectById(id) == null) {
            throw exception(OUTBOUND_NOT_EXISTS);
        }
    }

    @Override
    public List<OutboundInfoDO> getOutboundInfoList(Long outboundId) {
        return outboundInfoMapper.selectList(outboundId);
    }

    @Override
    public void deleteOutboundInfo(Long id) {
        // 校验存在
        this.validateOutboundInfoExists(id);
        // 删除
        outboundInfoMapper.deleteById(id);
    }

    @Override
    public void insertBatchInfo(Collection<OutboundInfoCreateReqVO> infoList) {
        // 校验物料编号存在
        for(OutboundInfoCreateReqVO info: infoList) {
            SparesDO spares = sparesMapper.selectByItemNo(info.getItemNo());
            if (spares == null) {
                throw exception(SPARES_ITEMNO_NOTEXISTS);
            }
        }
        // 插入
        List<OutboundInfoDO> list = OutboundInfoConvert.INSTANCE.convert2(infoList);
        this.outboundInfoMapper.insertBatch(list);
    }


    @Override
    public void updateOutboundInfo(OutboundInfoRespVO updateReqVO) {
        // 校验存在
        this.validateOutboundInfoExists(updateReqVO.getId());
        // 更新
        OutboundInfoDO updateObj = OutboundInfoConvert.INSTANCE.convert3(updateReqVO);
        outboundInfoMapper.updateById(updateObj);
    }

}
